package com.zuoban.storage.service.impl;

import com.zuoban.storage.properties.StorageProperties;
import com.zuoban.storage.service.StorageService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import java.io.InputStream;

/**
 * @BelongsProject: zuoban-boot
 * @BelongsPackage: com.zuoban.storage.service.impl
 * @Author: zxy
 * @CreateTime: 2022-10-10
 * @Description: ...
 */
public class MinioStorageServiceImpl implements StorageService {

    private final StorageProperties storageProperties;
    private final MinioClient minioClient;

    public MinioStorageServiceImpl(StorageProperties storageProperties) {
        this.storageProperties = storageProperties;
        this.minioClient = MinioClient.builder().endpoint(storageProperties.getMinio().getEndPoint())
                .credentials(storageProperties.getMinio().getAccessKey(), storageProperties.getMinio().getSecretKey()).build();
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            //如果BucketName不存在，则创建
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(storageProperties.getMinio().getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(storageProperties.getMinio().getBucketName()).build());
            }

            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(storageProperties.getMinio().getBucketName())
                            .object(path)
                            .stream(inputStream, inputStream.available(), -1)
                            .build()
            );

        } catch (Exception e) {
            throw new RuntimeException("上传文件失败：", e);
        }

        return storageProperties.getMinio().getEndPoint() + "/" + storageProperties.getMinio().getBucketName() + "/" + path;
    }
}
